package com.example.redistest.controller;

import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("redisLock")
public class RedisLockController {

    private static final Logger logger = LoggerFactory.getLogger(RedissonLockController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用 原生redis加锁   续命锁
     */
    @RequestMapping("/testlock")
    public String deductStock() throws InterruptedException {
        String lockKey = "product_001";
        String clientId = UUID.randomUUID().toString();     //使用uuid当作value，为finally释放锁做准备
        try {
            //使用setnx命令(若key不存在，则新增；存在，不做操作)，并设置失效时间
            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 10, TimeUnit.SECONDS);
            if (!result) {      //其他线程让其直接返回，保证只有一个线程 走下去
                return "errorCode:当前商品正在抢购，请稍后再试";
            }
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); //获取库存
            if (stock > 0) {
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock", realStock + "");         //设置最新库存
                System.out.println("扣减成功，剩余库存:" + realStock + "");
            } else {
                System.out.println("扣减失败，库存不足");
            }
        } finally {
            //  谁加的锁，谁释放(判断当前线程生成的锁是否是自己生成的)
            if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
                stringRedisTemplate.delete(lockKey);
            }
        }
        return "抢购成功";
    }


}
